import DataSet from './utils/dataset/dataSet';
import XLG from './utils/xlg/xlg'
import Message from './utils/message/index'

import generaSheet from './utils/xlg/generaSheet'
import cloud from 'cloud-uni'

window.MessageList = [];

function pArgs(args) {
  let result = "";
  for (let i = 0; i < args.length; i++) {
    if (typeof args[i] == "object") {
      result += JSON.stringify(args[i]);
    } else {
      result += args[i];
    }
    if (i < args.length - 1) {
      result += ","
    }
  }
  return result;
}

function postMessage(v, t) {
  MessageList.push(v)
}

const mainConsole = {
  log(str) {
    postMessage(["log", pArgs(arguments)], "*");
    console.log(str);
  },
  error(str) {
    console.log("pArgs(arguments)", pArgs(arguments))
    postMessage(["err", pArgs(arguments)], "*");
    console.error(str);
  },
  info(str) {
    postMessage(["info", pArgs(arguments)], "*");
    console.info(str);
  }
}

//公共函数库放到上面了
const commonMain = {
  console: mainConsole,
  ...window.codelist,
  DataSet,
  XLG,
  generaSheet,
  ...Message
};

/**
 * 运行函数
 * @param code  代码字符串
 * @param params 执行参数对象
 */
const $codeRun = function (code = '', params = {}) {
  try {
    cloud.createContext({
      ...commonMain,
      $params: params
    });

    //查找替换 添加异步方法
    let runtime = `
    async function run() {
      ${code}
    }
    return run();
    `

    let returned = cloud.runInContext(runtime, {
      ...commonMain,
      $params: params
    });
    return returned;
  } catch (e) {
    mainConsole.error(e.message)
  }
}


if (window && window.$codeRun === undefined) {
  window.$codeRun = $codeRun
}

if (window.parent && window.parent.window.$codeRun === undefined) {
  window.parent.window.$codeRun = $codeRun
}

export default $codeRun
